package items

import (
	"server/game/cache"
	"server/share/config"

	"github.com/hwcer/yyds"
	"github.com/hwcer/yyds/context"
	"github.com/hwcer/yyds/errors"
)

/**
 * @name Box
 * @param string key 物品唯一ID,用','分割。
 * 打开礼盒
 */

func (this *items) Box(c *context.Context) interface{} {
	args := &Args{}
	if err := c.Bind(args); err != nil {
		return err
	}
	if args.Key == "" {
		return errors.ErrArgEmpty
	}
	if args.Num <= 0 {
		return c.Error("num error")
	}
	if args.Num > itemsUseMaxNum {
		args.Num = itemsUseMaxNum
	}

	itemsColl := cache.GetItems(c.Player.Updater)
	d := itemsColl.Get(args.Key)
	if d == nil {
		return errors.ErrDataNotExists
	}
	if !yyds.Config.Is(d.IID, config.ITypeBox) {
		return c.Error("not box")
	}
	if d.Value < int64(args.Num) {
		return errors.ErrItemNotEnough
	}

	cfg := config.Data.Box[d.IID]
	if cfg == nil {
		return c.Error("id not exist")
	} else if len(cfg.ItemList) == 0 {
		return c.Error("config Box ItemList error")
	}

	itemsColl.Sub(d.IID, args.Num)
	switch cfg.Type {
	case 1:
		use := int32(0)
		for _, v := range args.Attach {
			use += v
		}
		if use != args.Num {
			return c.Error("选择的物品数量和使用的物品数量不匹配")
		}
		group := config.GetItemRandom()
		if group == nil {
			return c.Error("GetItemRandom error")
		}
		options := map[int32]int32{}
		list := cfg.ItemList[0]
		w := group.Bong[list.Id]
		if w == nil {
			return c.Errorf(0, "GetItemRandom error:%d", list.Id)
		}
		w.Range(func(k int32, _ int32) bool {
			if itemGroupBong := config.Data.ItemGroupBong[k]; itemGroupBong != nil {
				options[itemGroupBong.Key] = itemGroupBong.Num
			}
			return true
		})
		for k, v := range args.Attach {
			if n, ok := options[k]; !ok {
				return c.Errorf(0, "choose item not exist:%d", k)
			} else {
				c.Player.Add(k, v*n)
			}
		}

	default:
		for i := int32(0); i < args.Num; i++ {
			c.Player.AddItems(cfg.ItemList)
		}

	}
	return true
}
